﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CdcSoftware.Pivotal.Engine.Client.Services.Forms;
using CdcSoftware.Pivotal.Applications.Core.Client;
using CdcSoftware.Pivotal.Engine.UI.DataTypes.Navigation;
using System.Data;
using CdcSoftware.Pivotal.Applications.Core.Common;
using CdcSoftware.Pivotal.Engine.UI.Forms;
using CdcSoftware.Pivotal.Engine;
using CdcSoftware.Pivotal.Engine.Client.Services.Interfaces;
using System.Windows.Forms;
using Microsoft.PointOfService;

namespace Pcm.Retail.Client.FormTasks
{
    public partial class RETender : FormClientTask
    {
        #region Variables
        #endregion

        #region Public methods
        /// <summary>
        /// Save a new record into database
        /// </summary>
        /// <history>
        /// #Revision   Date        Author  Description
        /// 6.0.12.1   11/02/2013  DS      Initial Version
        /// </history>
        public virtual bool AddRecord()
        {
            bool saveRecord = false;
            try
            {
                saveRecord = base.SaveRecord();
            }
            catch (Exception exc)
            {

                Globals.HandleException(exc);
            }
            return saveRecord;

        }

        /// <summary>
        /// This method gets called when the form meta data and data have both been loaded,
        /// and the form UI has finished drawing. Override this method to perform custom
        /// form initialization.
        /// </summary>
        /// <history>
        /// #Revision   Date        Author  Description
        /// 6.0.0.0     08/01/2011  BR      Initial Version
        /// </history>
        public override void OnFormInitialized()
        {
            try
            {
                base.OnFormInitialized();

                if (this.TaskPad != null)
                {
                    this.TaskPad.Visible = false;
                    // Or remove the TaskPad
                    this.TaskPad.SuspendNotifications();

                    foreach (TaskPadGroup taskPadGroup in this.TaskPad.TaskPadGroups)
                    {
                        taskPadGroup.Items.Clear();
                    }
                    this.TaskPad.TaskPadGroups.Clear();
                    this.TaskPad.ResumeNotifications();
                }

                Globals.RemoveButtonBarButton(new string[] { "Save", "Apply", "Cancel", "Delete", "Refresh" });

                SharedLoad();                
                
                this.FormView.Dirty = false;
                this.FormControl.GetControlByName("btnCash").Focus();

                //Reprint the receipt.
                if (this.TransitionPointParameter.HasValidParameters() && this.TransitionPointParameter.CheckUserDefinedParameterNumber(4) &&
                    string.Equals(TypeConvert.ToString(this.TransitionPointParameter.GetUserDefinedParameter(4)), "REPRINT"))
                {      
                    //InitializeAndPrintReceipt(false, true, TypeConvert.ToBoolean(this.PrimaryDataRow["RE_Gift"]));
                    Globals.ShowReport("RE_Receipt", RecordFilter.IndividualRecord, this.RecordId, null);
                    //Close the Tender form after printing the receipt.
                    this.FormView.CloseForm(true);
                }
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc);
            }
        }

        /// <summary>
        /// Event fires when we refresh the form.
        /// </summary>
        public override void OnFormReloaded()
        {
            try
            {
                base.OnFormReloaded();

                SharedLoad();
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc);
            }
        }

        /// <summary>
        /// This function updates the Form
        /// </summary>
        /// <history>
        /// #Revision   Date        Author  Description
        /// 6.0.12.1   11/02/2013  DS      Initial Version
        /// </history>
        public override bool SaveRecord()
        {
            bool saveRecord = false;

            try
            {
                if (this.RecordId == null)
                {
                    FormService.SaveRecord(FormData);
                    saveRecord = this.AddRecord();
                }
                else
                {
                    saveRecord = base.SaveRecord();
                }
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc);
            }
            return saveRecord;
        }

        #region Receipt Printing

        /// <summary>
        /// Initialize the printer device.
        /// </summary>
        /// <returns></returns>
        //public static PosPrinter GetReceiptPrinter()
        //{
        //    Configuration config = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location);
        //    XmlDocument doc = new XmlDocument();
        //    doc.Load(config.FilePath);
        //    XmlNode bNode = doc.SelectSingleNode("descendant::NetFx40_LegacySecurityPolicy");
        //    if (bNode == null)
        //    {
        //        XmlNode runtime = doc.SelectSingleNode("configuration/runtime");
        //        XmlNode legacySwitch = doc.CreateNode(XmlNodeType.Element, "NetFx40_LegacySecurityPolicy", null);
        //        XmlAttribute value = doc.CreateAttribute("enabled");
        //        value.Value = "true";
        //        legacySwitch.Attributes.Append(value);
        //        runtime.AppendChild(legacySwitch);
        //        doc.Save(config.FilePath);
        //        ConfigurationManager.RefreshSection("runtime");
        //        config.Save();
        //    }

        //    PosExplorer posExplorer = new PosExplorer();
        //    DeviceCollection devices = posExplorer.GetDevices(DeviceType.PosPrinter);
        //    DeviceInfo receiptPrinterDevice = posExplorer.GetDevice("PosPrinter", "PosPrinter");// "EPSON TM-T88IV Receipt", May need to change this if you don't use a logicial name or use a different one.
        //    return (PosPrinter)posExplorer.CreateInstance(receiptPrinterDevice);
        //}

        /// <summary>
        /// Initialize the printer and fire the proper print command.
        /// </summary>
        /// <param name="exchange">Is this an Exchange sale?</param>
        /// <param name="rePrint">Is this an reprint?</param>
        /// <param name="gift">Is this a gift sale?</param>
        public void InitializeAndPrintReceipt(bool exchange, bool rePrint, bool gift)
        {
            try
            {
                //DS: Now the POSHardwares are working on the new AppDomain. So pass complete data required to Print to the new AppDomain.
                DataTable quantity = null;
                DataTable receiptData = Globals.GetDataTable("RE_Order Products with OrderId?", new object[] { Id.Create(this.PrimaryDataRow["SFA_Order_Id"]) }, new string[] { });

                DataTable lobTC = Globals.GetDataTable("RE_Terms and Conditions for LOB?", new object[] { this.PrimaryDataRow["RE_LOB_Id"] },
                                            "Terms_And_Conditions", "Serial_Number");

                DataTable staffPurchaseQuota = Globals.GetDataTable("RE_Staff Purchase Profile Quota for Staff ? LOB ?",
                    new object[] { this.PrimaryDataRow["RE_Staff_Customer_Id"], this.PrimaryDataRow["RE_LOB_Id"] }, "Quota", "Discount_Condition_Id");

                if (staffPurchaseQuota != null && staffPurchaseQuota.Rows.Count > 0)
                {
                    quantity = Globals.GetDataTable("RE_Staff Purchase with Staff ?  Discount Condition ? Year ?", new object[] { this.PrimaryDataRow["RE_Staff_Customer_Id"], 
                        staffPurchaseQuota.Rows[0]["Discount_Condition_Id"], DateTime.Now.Year }, DateTime.Now.ToString("MMM") + "_Qty");
                }

                object gstPercent = Globals.ServerSqlIndex("RE_Line_Of_Business", "Tax_Percentage", Id.Create(this.PrimaryDataRow["RE_LOB_Id"]));

                //Perform the Print Activity.
                //DS: Now the POSHardwares are working on the new AppDomain.
                PosHardware.PerformActivity<PivotalPrinter>("PosPrinter", false, this.DataSet, exchange, rePrint, gift, receiptData, lobTC, staffPurchaseQuota, quantity, gstPercent);
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex);
            }
        }

        /// <summary>
        /// Prints the receipt.
        /// </summary>
        /// <param name="exchange">Is this an Exchange sale?</param>
        /// <param name="rePrint">Is this an reprint?</param>
        /// <param name="gift">Is this a gift sale?</param>
        public void PrintReceipt(PosPrinter printer, bool exchange, bool rePrint, bool gift, DataSet TenderDataset, DataTable receiptData, DataTable lobTC, DataTable staffPurchaseQuota,
            DataTable quantity, object gstPercent)
        {
            //DS: Now getting all these data as Parameter as this is working in the new AppDoamain.
            //DataTable receiptData = Globals.GetDataTable("RE_Order Products with OrderId?", new object[] { Id.Create(TenderDataset.Tables[0].Rows[0]["SFA_Order_Id"]) }, new string[] { });
            if (receiptData != null)
            {
                if (receiptData.Rows.Count > 0)
                {
                    if (!Convert.IsDBNull(TenderDataset.Tables[0].Rows[0]["RE_LOB_Id"]))
                    {
                        //DS: Now getting all these data as Parameter as this is working in the new AppDoamain.
                        //Get the terms and conditions
                        //DataTable lobTC = Globals.GetDataTable("RE_Terms and Conditions for LOB?", new object[] { TenderDataset.Tables[0].Rows[0]["RE_LOB_Id"] },
                        //    "Terms_And_Conditions", "Serial_Number");

                        //Sort the TC with the serial number
                        if (lobTC != null && lobTC.Rows.Count > 0)
                            sortedTC = lobTC.AsEnumerable().OrderBy(a => a["Serial_Number"]);
                    }

                    //Print Header
                    Globals.PrintReceiptHeader(printer, TypeConvert.ToString(receiptData.Rows[0]["Store_Name"]), TypeConvert.ToString(receiptData.Rows[0]["Receipt_Address"]),
                        TypeConvert.ToString(receiptData.Rows[0]["Store_Phone"]), TypeConvert.ToString(receiptData.Rows[0]["Tax_Reference_No"]),
                        TypeConvert.ToString(receiptData.Rows[0]["Customer_Service_Phone"]), TypeConvert.ToString(receiptData.Rows[0]["Email"]),
                        TypeConvert.ToDateTime(receiptData.Rows[0]["RE_Order_Date"]), TypeConvert.ToString(receiptData.Rows[0]["Staff_First_Name"]),
                        TypeConvert.ToString(receiptData.Rows[0]["RE_Receipt_Number"]), (receiptData.Rows[0]["Rcpt_Store_Logo"]), gift);
                    Globals.PrintTextLine(printer, new string('_', printer.RecLineChars));

                    //Print each line item.
                    foreach (DataRow dr in receiptData.Rows)
                    {
                        Globals.PrintLineItem(printer, TypeConvert.ToString(dr["RE_Article_Number"]), TypeConvert.ToString(dr["Color_Description"]),
                            TypeConvert.ToInt16(dr["Quantity"]), TypeConvert.ToDouble(dr["RE_Extended_Price"]), dr["Disct_Condition1_ConditionID"],
                            TypeConvert.ToString(dr["Disct_Condition1_Value_Type"]), TypeConvert.ToDouble(dr["Disct_Condition1_Percent_Value"]),
                            TypeConvert.ToDouble(dr["Disct_Condition1_Amount"]), TypeConvert.ToDouble(dr["Tier1_Discount_Value"]),
                            TypeConvert.ToString(dr["Disct_Condition1_Description"]), dr["Disct_Condition2_ConditionID"],
                            TypeConvert.ToString(dr["Disct_Condition2_Value_Type"]), TypeConvert.ToDouble(dr["Disct_Condition2_Percent_Value"]),
                            TypeConvert.ToDouble(dr["Disct_Condition2_Amount"]), TypeConvert.ToDouble(dr["Tier2_Discount_Value"]),
                            TypeConvert.ToString(dr["Disct_Condition2_Description"]), TypeConvert.ToString(dr["Item_Description"]),
                            TypeConvert.ToString(dr["Size_Description"]), gift, TypeConvert.ToString(dr["RE_Staff_Code"]));
                    }

                    Globals.PrintTextLine(printer, new string('_', printer.RecLineChars));

                    //Print Totals section.
                    //DS: Now getting all these data as Parameter as this is working in the new AppDoamain.
                    //Get the GST Tax percent from Employee.
                    //object gstPercent = Globals.ServerSqlIndex("RE_Line_Of_Business", "Tax_Percentage", Id.Create(TenderDataset.Tables[0].Rows[0]["RE_LOB_Id"]));

                    Globals.PrintTotals(printer, TypeConvert.ToDouble(receiptData.Rows[0]["Quote_Total"]), TypeConvert.ToDouble(receiptData.Rows[0]["Total_Taxes"]),
                        TypeConvert.ToInt32(receiptData.Rows[0]["RE_Total_Qty"]), TypeConvert.ToDouble(gstPercent), gift);

                    Globals.PrintTextLine(printer, new string('_', printer.RecLineChars));

                    //Print Tender details.
                    if (!gift)
                    {
                        //Then only print the tender information.
                        Globals.PrintTender(printer, TenderDataset.Tables["RE_Order_Tender_Order_Id"]);

                        //Print Membership details.
                        if (string.Equals(TypeConvert.ToString(receiptData.Rows[0]["RE_Customer_Type"]), "Member"))
                        {
                            //Verify whether to print the Birthday image or not.
                            if (TypeConvert.ToDateTime(receiptData.Rows[0]["Contact_Birthday"]).Month == DateTime.Today.Month)
                                Globals.PrintPrivilegeCardDetails(printer, TypeConvert.ToString(receiptData.Rows[0]["First_Name"]),
                                    TypeConvert.ToString(receiptData.Rows[0]["Last_Name"]), TypeConvert.ToString(receiptData.Rows[0]["RE_Membership_ID"]),
                                    true, receiptData.Rows[0]["Rcpt_Bday_Wish_Image"]);
                            else
                                Globals.PrintPrivilegeCardDetails(printer, TypeConvert.ToString(receiptData.Rows[0]["First_Name"]),
                                    TypeConvert.ToString(receiptData.Rows[0]["Last_Name"]), TypeConvert.ToString(receiptData.Rows[0]["RE_Membership_ID"]), false, null);
                        }
                        else if (string.Equals(TypeConvert.ToString(receiptData.Rows[0]["RE_Customer_Type"]), "Staff"))
                        {
                            int remainingQuota = 0;

                            //DS: Now getting all these data as Parameter as this is working in the new AppDoamain.
                            //Calculate remainingQuota
                            //DataTable staffPurchaseQuota = Globals.GetDataTable("RE_Staff Purchase Profile Quota for Staff ? LOB ?",
                            //    new object[] { TenderDataset.Tables[0].Rows[0]["RE_Staff_Customer_Id"], TenderDataset.Tables[0].Rows[0]["RE_LOB_Id"] }, "Quota", "Discount_Condition_Id");

                            if (staffPurchaseQuota != null && staffPurchaseQuota.Rows.Count > 0)
                            {
                                //DS: Now getting all these data as Parameter as this is working in the new AppDoamain.
                                //DataTable quantity = Globals.GetDataTable("RE_Staff Purchase with Staff ?  Discount Condition ? Year ?",
                                //    new object[] { TenderDataset.Tables[0].Rows[0]["RE_Staff_Customer_Id"], staffPurchaseQuota.Rows[0]["Discount_Condition_Id"], DateTime.Now.Year },
                                //    DateTime.Now.ToString("MMM") + "_Qty");

                                if (quantity != null && quantity.Rows.Count == 1)
                                    remainingQuota = TypeConvert.ToInt32(staffPurchaseQuota.Rows[0]["Quota"]) - TypeConvert.ToInt32(quantity.Rows[0][DateTime.Now.ToString("MMM") + "_Qty"]);
                            }

                            //Print Staff Details.
                            Globals.PrintStaffDetails(printer, TypeConvert.ToString(TenderDataset.Tables[0].Rows[0]["RE_Staff_Customer_FN_LN"]), false, remainingQuota);
                        }
                        else if (string.Equals(TypeConvert.ToString(receiptData.Rows[0]["RE_Customer_Type"]), "Top Management"))
                        {
                            //Print Top Management Details.
                            Globals.PrintStaffDetails(printer, TypeConvert.ToString(TenderDataset.Tables[0].Rows[0]["RE_Top_Management_FN_LN"]), true, null);
                        }

                        Globals.PrintTextLine(printer, new string('_', printer.RecLineChars));
                    }

                    //DS: For exchange CK does not need 'EXCHANGE RECEIPT' to be printed. So the exchange boolean is passed as false.
                    exchange = false;
                    //Print Footer
                    Globals.PrintReceiptFooter(printer, TypeConvert.ToString(receiptData.Rows[0]["Rcpt_Thank_You_Note"]), sortedTC,
                        TypeConvert.ToString(receiptData.Rows[0]["Website"]), TypeConvert.ToString(TenderDataset.Tables[0].Rows[0]["RE_Receipt_Number"]),
                        receiptData.Rows[0]["Rcpt_Promo_Image"], exchange, rePrint, gift);
                }
            }
            printer.CutPaper(95); //Print 'advance and cut' escape command. 
        }
        #endregion
        #endregion

        #region Private Methods.
        /// <summary>
        /// Common code shared.
        /// </summary>
        private void SharedLoad()
        {
            //Disabling cancel button for all cases
            this.FormControl.GetControlByName("btnCancel").Enabled = false;

            //Buttons need to be disabled separately since disconnected fields
            List<string> tenderBtns = new List<string>();

            tenderBtns.Add("btnCash");
            tenderBtns.Add("btnBack");
            tenderBtns.Add("btnNETS");
            tenderBtns.Add("btnVouchers");
            tenderBtns.Add("btnVISA");
            tenderBtns.Add("btnMaster");
            tenderBtns.Add("btnAmex");
            tenderBtns.Add("btnIPP");
            tenderBtns.Add("btnCancel");
            tenderBtns.Add("btnCUP");
            tenderBtns.Add("btnProcess");
            tenderBtns.Add("btnOthers");            

            //Status = Processed
            if (TypeConvert.ToString(this.PrimaryDataRow["RE_Order_Status"]) == "Processed" || TypeConvert.ToString(this.PrimaryDataRow["RE_Order_Status"]) == "Void")
            {
                //Open the form in read-only mode for Status = Processed
                Globals.EnableDisableAllFields(false, false, false);

                foreach (string str in tenderBtns)
                {
                    this.FormControl.GetControlByName(str).Enabled = false;
                }

                //Enalbing Apple Care Button when sale is processed.
                this.FormControl.GetControlByName("btnAppleCare").Enabled = true;
            }
            else
            {
                if (TypeConvert.ToString(this.PrimaryDataRow["RE_Type"]) == "Refund")
                {
                    //this.PrimaryDataRow["RE_Tendered_Amount"] = TypeConvert.ToDouble(this.PrimaryDataRow["Quote_Total"]);
                    //this.PrimaryDataRow["RE_Balance_Amount"] = 0;
                    this.FormControl.GetControlByName(tenderBtns[3]).Enabled = false;
                    //DS: 20052013 - For source order involving IPP, refund also needs to be through IPP. So enabling the Button only when there is a IPP involved.
                    if (this.DataSet.Tables["SFA_Order__Product_SFA_Order_I"].AsEnumerable().Count(a => string.Equals(TypeConvert.ToString(a["RE_Product_Type"]).ToUpper(), "FEES FOR IPP")) > 0)
                        this.FormControl.GetControlByName(tenderBtns[7]).Enabled = true;
                    else 
                        this.FormControl.GetControlByName(tenderBtns[7]).Enabled = false;
                }
                this.PrimaryDataRow["RE_Balance_Amount"] = TypeConvert.ToDouble(this.PrimaryDataRow["Quote_Total"]);
                this.PrimaryDataRow["RE_Tendered_Amount"] = 0;

                if (!Convert.IsDBNull(this.PrimaryDataRow["RE_Sale_Deposit_Link_Id"]))
                {
                    this.FormControl.GetControlByName(tenderBtns[0]).Enabled = false;
                    this.FormControl.GetControlByName(tenderBtns[2]).Enabled = false;
                    this.FormControl.GetControlByName(tenderBtns[3]).Enabled = false;
                    this.FormControl.GetControlByName(tenderBtns[4]).Enabled = false;
                    this.FormControl.GetControlByName(tenderBtns[5]).Enabled = false;
                    this.FormControl.GetControlByName(tenderBtns[6]).Enabled = false;
                    this.FormControl.GetControlByName(tenderBtns[7]).Enabled = false;
                    this.FormControl.GetControlByName(tenderBtns[9]).Enabled = false;
                    this.FormControl.GetControlByName(tenderBtns[11]).Enabled = false;
                    this.PrimaryDataRow["RE_Balance_Amount"] = 0;

                    if (string.Equals(TypeConvert.ToString(this.PrimaryDataRow["RE_Customer_Type"]), "Walk-In"))
                    {
                        //Set the contact details if they were set in the earlier Deposit.
                        DataTable depositOrder = Globals.GetDataTable("RE_Orders for Order Id?", new object[] { this.PrimaryDataRow["RE_Sale_Deposit_Link_Id"] },
                            "RE_Contact_First_Name", "RE_Contact_Last_Name", "RE_Contact_Email", "RE_Contact_Mobile_Phone", "RE_Contact_Home_Phone", "RE_Contact_Address");
                        if (depositOrder != null && depositOrder.Rows.Count == 1)
                        {
                            this.PrimaryDataRow["RE_Contact_First_Name"] = depositOrder.Rows[0]["RE_Contact_First_Name"];
                            this.PrimaryDataRow["RE_Contact_Last_Name"] = depositOrder.Rows[0]["RE_Contact_Last_Name"];
                            this.PrimaryDataRow["RE_Contact_Email"] = depositOrder.Rows[0]["RE_Contact_Email"];
                            this.PrimaryDataRow["RE_Contact_Mobile_Phone"] = depositOrder.Rows[0]["RE_Contact_Mobile_Phone"];
                            this.PrimaryDataRow["RE_Contact_Home_Phone"] = depositOrder.Rows[0]["RE_Contact_Home_Phone"];
                            this.PrimaryDataRow["RE_Contact_Address"] = depositOrder.Rows[0]["RE_Contact_Address"];
                        }
                    }
                }

                //Enabling cancel button only for existing record whose Status is either "Hold" or "Pending"
                if (this.RecordId != null && (TypeConvert.ToString(this.PrimaryDataRow["RE_Order_Status"]) == "Hold" ||
                    TypeConvert.ToString(this.PrimaryDataRow["RE_Order_Status"]) == "Pending"))
                    this.FormControl.GetControlByName("btnCancel").Enabled = true;

                //Disabling Apple Care Button if Sale is not Processed.
                this.FormControl.GetControlByName("btnAppleCare").Enabled = false;


                if (string.Equals(TypeConvert.ToString(this.PrimaryDataRow["RE_Customer_Type"]), "Member") && !Convert.IsDBNull(this.PrimaryDataRow["Bill_To_Contact_Id"]))
                {
                    //Fill-in the customer information in the section and make the entire section read-only.
                    DataTable member = Globals.GetDataTable("Contact", new List<NameValuePair>() { new NameValuePair("Contact_Id", this.PrimaryDataRow["Bill_To_Contact_Id"]) });
                    if (member != null && member.Rows.Count > 0)
                    {
                        this.PrimaryDataRow["RE_Contact_First_Name"] = member.Rows[0]["First_Name"];
                        this.PrimaryDataRow["RE_Contact_Last_Name"] = member.Rows[0]["Last_Name"];
                        this.PrimaryDataRow["RE_Contact_Email"] = member.Rows[0]["Email"];
                        this.PrimaryDataRow["RE_Contact_Mobile_Phone"] = member.Rows[0]["Mobile"];
                        this.PrimaryDataRow["RE_Contact_Home_Phone"] = member.Rows[0]["Phone"];
                        this.PrimaryDataRow["RE_Contact_Address"] = member.Rows[0]["Address_1"];
                        ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Contact_First_Name")).ReadOnly = true;
                        ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Contact_Last_Name")).ReadOnly = true;
                        ((PivotalEmail)this.FormControl.GetControlByDataName("RE_Contact_Email")).ReadOnly = true;
                        ((PivotalNumber)this.FormControl.GetControlByDataName("RE_Contact_Mobile_Phone")).ReadOnly = true;
                        ((PivotalNumber)this.FormControl.GetControlByDataName("RE_Contact_Home_Phone")).ReadOnly = true;
                        ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Contact_Address")).ReadOnly = true;
                    }
                }
                else
                {
                    ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Contact_First_Name")).ReadOnly = false;
                    ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Contact_Last_Name")).ReadOnly = false;
                    ((PivotalEmail)this.FormControl.GetControlByDataName("RE_Contact_Email")).ReadOnly = false;
                    ((PivotalNumber)this.FormControl.GetControlByDataName("RE_Contact_Mobile_Phone")).ReadOnly = false;
                    ((PivotalNumber)this.FormControl.GetControlByDataName("RE_Contact_Home_Phone")).ReadOnly = false;
                    ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Contact_Address")).ReadOnly = false;
                }

                //NN 11062013:Added Code to set Contact fields required when Apple Care Product is added as secondary Order Products.
                this.SetContactRequired();
            }

            ((PivotalNumber)this.FormControl.GetControlByDataName("RE_Points_For_Order")).Focus();
        }

        /// <summary>
        /// Common method for setting a particular Tender type and record add
        /// </summary>
        /// <param name="tenderType"></param>
        private void AddRecordForTenderType(string tenderType)
        {
            try
            {
                DataTable tenders = this.FormData.DataSet.Tables["RE_Order_Tender_Order_Id"];
                //If condition modified for Refund section. Will allow record to be created for Refund on Credit button click
                //Create a record only if RE_Balance_Amount is not 0.0 i.e. greater than 0.0 
                if (TypeConvert.ToDouble(this.PrimaryDataRow["RE_Balance_Amount"]) > 0
                    || (TypeConvert.ToDouble(this.PrimaryDataRow["RE_Balance_Amount"]) <= 0 && TypeConvert.ToString(this.PrimaryDataRow["RE_Type"]) == "Refund"))
                {
                    if (String.Equals(tenderType.ToUpper(), "VOUCHER"))
                    {
                        base.NewSecondaryRecord("RE_Order_Tender_Order_Id");
                        tenders.Rows[tenders.Rows.Count - 1]["Voucher"] = 1;
                        //Set the Tender Type record as RE_Tender_Type.Type = tenderType and Default = True
                        DataTable tender = Globals.GetDataTable("RE_Non-system Default Tender with Type?", new object[] { tenderType.ToUpper() }, "RE_Tender_Type_Id");
                        if (tender != null && tender.Rows.Count == 1)
                            tenders.Rows[tenders.Rows.Count - 1]["Tender_Type_Id"] = tender.Rows[0]["RE_Tender_Type_Id"];

                        //Only for Refund Sale, set the Refund field to true
                        if (TypeConvert.ToString(this.PrimaryDataRow["RE_Type"]) == "Refund")
                            tenders.Rows[tenders.Rows.Count - 1]["Refund"] = 1;
                        else
                            tenders.Rows[tenders.Rows.Count - 1]["Refund"] = 0;

                        tenders.Rows[tenders.Rows.Count - 1]["Currency_Id"] = this.PrimaryDataRow["RE_Store_Id__Currency_Id"];
                        if (TypeConvert.ToBoolean(tenders.Rows[tenders.Rows.Count - 1]["Tender_Type_Id__Default_"]))
                            EnableDisableDataGridCell(false, tenders.Rows.Count - 1, "RE_Order_Tender_Order_Id", "Tendered_Amount");
                        else
                            EnableDisableDataGridCell(true, tenders.Rows.Count - 1, "RE_Order_Tender_Order_Id", "Tendered_Amount");
                        EnableDisableDataGridCell(true, tenders.Rows.Count - 1, "RE_Order_Tender_Order_Id", "Reference_Id", "Voucher_Type", "Voucher_Bank");
                        BeginEditSecondaryCell("RE_Order_Tender_Order_Id", "Reference_Id", tenders.Rows.Count - 1);
                        return;
                    }

                    if (tenders.AsEnumerable().Count(a => TypeConvert.ToString(a["Tender_Type_Id__Tender_Type"]).ToUpper() == tenderType.ToUpper()) == 0)
                    {
                        //DS: 22052013 - For refund allow multiple tender modes.
                        //For Refund only one row of tender is allowed
                        //if (TypeConvert.ToString(this.PrimaryDataRow["RE_Type"]) == "Refund" && tenders.Rows.Count == 1)
                        //{
                        //    PivotalMessageBox.Show("For Refund case, only one Tender is accepted.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        //    return;
                        //}
                        base.NewSecondaryRecord("RE_Order_Tender_Order_Id");
                        //Default the Tendered Amount (-ve) with RE_Tender_Amount for Refund since Bal Amount = 0
                        if (TypeConvert.ToString(this.PrimaryDataRow["RE_Type"]) == "Refund")
                        {
                            //As we are allowing the cashier to enter tenders for Refund case also.
                            //tenders.Rows[tenders.Rows.Count - 1]["Tendered_Amount"] = TypeConvert.ToDouble(this.PrimaryDataRow["RE_Tendered_Amount"]);
                            //tenders.Rows[tenders.Rows.Count - 1]["Tendered_Amount"] = TypeConvert.ToDouble(this.PrimaryDataRow["RE_Balance_Amount"]);
                            tenders.Rows[tenders.Rows.Count - 1]["Refund"] = 1;
                            //EnableDisableDataGridCell(false, tenders.Rows.Count - 1, "RE_Order_Tender_Order_Id", "Tendered_Amount");
                        }
                        else
                        {
                            //tenders.Rows[tenders.Rows.Count - 1]["Tendered_Amount"] = TypeConvert.ToDouble(this.PrimaryDataRow["RE_Balance_Amount"]);
                            tenders.Rows[tenders.Rows.Count - 1]["Refund"] = 0;
                        }
                        tenders.Rows[tenders.Rows.Count - 1]["Tendered_Amount"] = TypeConvert.ToDouble(this.PrimaryDataRow["RE_Balance_Amount"]);

                        if (String.IsNullOrWhiteSpace(tenderType))
                            tenders.Rows[tenders.Rows.Count - 1]["Tender_Type_Id"] = DBNull.Value;
                        else
                        {
                            //Set the Tender Type record as RE_Tender_Type.Type = tenderType and Default = True
                            DataTable tender = Globals.GetDataTable("RE_Non-system Default Tender with Type?", new object[] { tenderType.ToUpper() }, "RE_Tender_Type_Id");
                            if (tender != null && tender.Rows.Count == 1)
                                tenders.Rows[tenders.Rows.Count - 1]["Tender_Type_Id"] = tender.Rows[0]["RE_Tender_Type_Id"];
                        }
                        tenders.Rows[tenders.Rows.Count - 1]["Currency_Id"] = this.PrimaryDataRow["RE_Store_Id__Currency_Id"];
                        tenders.Rows[tenders.Rows.Count - 1]["Voucher"] = 0;
                        EnableDisableDataGridCell(false, tenders.Rows.Count - 1, "RE_Order_Tender_Order_Id", "Reference_Id", "Voucher_Type", "Voucher_Bank");
                        BeginEditSecondaryCell("RE_Order_Tender_Order_Id", "Tendered_Amount", tenders.Rows.Count - 1);

                        TotalsCalculations();
                    }
                    else
                        PivotalMessageBox.Show("Selected Type is already present. You can modify the Amount if required.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                    //Allow user to add tenders for Refund transactions even of Balance is 0
                    if (TypeConvert.ToString(this.PrimaryDataRow["RE_Type"]) != "Refund")
                        PivotalMessageBox.Show("Can add Tenders only if Balance Amount is more than 0.", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc);
            }
        }

        /// <summary>
        /// Enable/Disable a particular datagrid cell.
        /// </summary>
        /// <param name="secondaryName">Secondary Data Name</param>
        /// <param name="cellName">Cell name to be made read-only.</param>
        /// <param name="rowIndex">Row index for the cell.</param>
        /// <param name="enableCell">true, will enable the field for editing.</param>
        private void EnableDisableDataGridCell(bool enableCell, int rowIndex, string secondaryName, params string[] cellNames)
        {
            IFormView formView = (IFormView)ClientContext.ClientAPIService.GetActiveContentObject();
            CdcSoftware.Pivotal.Engine.UI.Forms.PivotalClientFormControl formControl = (CdcSoftware.Pivotal.Engine.UI.Forms.PivotalClientFormControl)formView.FormControl;

            // Get the Secondary Segment into a PivotalSecondary object...
            CdcSoftware.Pivotal.Engine.UI.Forms.PivotalSecondary secondary = formControl.GetSecondary(secondaryName);

            if (secondary != null)
            {
                foreach (string cell in cellNames)
                {
                    secondary.Rows[rowIndex].Cells[cell].ReadOnly = !enableCell;
                }
            }
        }

        /// <summary>
        /// Add Miscellaneous Income Row to the Tender Grid.
        /// </summary>
        /// <param name="orderTender">Tender datatable</param>
        /// <param name="extraAmt">Extra amount to be added as Misc. Income.</param>
        /// <history>
        /// #Revision   Date        Author  Description
        /// 6.0.12.1    11/02/2013  DS      Initial Version
        /// </history>
        private void AddMiscIncome(double extraAmt)
        {
            DataTable miscIncomeProduct = Globals.GetDataTable("RE_Products with Type as Misc Income", new object[] { }, "Product_Id");
            if (miscIncomeProduct != null && miscIncomeProduct.Rows.Count == 1)
            {
                //Find the Tax Percentage
                double taxPercentage = TypeConvert.ToDouble(Globals.ServerSqlIndex("Employee", "RE_Tax_Rate", SystemClient.UserProfile.EmployeeId));
                //Add a new row to the SFA_Order__Product Table.
                DataTable orderProduct = this.DataSet.Tables["SFA_Order__Product_SFA_Order_I"];
                base.NewSecondaryRecord("SFA_Order__Product_SFA_Order_I");
                orderProduct.Rows[orderProduct.Rows.Count - 1]["Product_Id"] = miscIncomeProduct.Rows[0]["Product_Id"];
                //orderProduct.Rows[orderProduct.Rows.Count - 1]["RE_Product_SKU_Id"] = this.PrimaryDataRow["RE_LOB_Id__Misc_Income_SKU"];
                //orderProduct.Rows[orderProduct.Rows.Count - 1]["Product_Id"] = Globals.ServerSqlIndex("RE_Product_SKU", "Product_Id",
                //    Id.Create(this.PrimaryDataRow["RE_LOB_Id__Misc_Income_SKU"]));
                orderProduct.Rows[orderProduct.Rows.Count - 1]["RE_Product_Type"] = "Miscellaneous Income";
                orderProduct.Rows[orderProduct.Rows.Count - 1]["RE_Invisible"] = 1;
                orderProduct.Rows[orderProduct.Rows.Count - 1]["RE_Exclude_In_Net_Sales"] = 1;
                orderProduct.Rows[orderProduct.Rows.Count - 1]["RE_Staff_Code"] = orderProduct.Rows[orderProduct.Rows.Count - 2]["RE_Staff_Code"];
                orderProduct.Rows[orderProduct.Rows.Count - 1]["RE_Staff_Id"] = orderProduct.Rows[orderProduct.Rows.Count - 2]["RE_Staff_Id"];
                orderProduct.Rows[orderProduct.Rows.Count - 1]["Quantity"] = 1;
                orderProduct.Rows[orderProduct.Rows.Count - 1]["Unit_Price"] = extraAmt;
                orderProduct.Rows[orderProduct.Rows.Count - 1]["RE_Extended_Price"] = extraAmt;
                orderProduct.Rows[orderProduct.Rows.Count - 1]["Tax_Percentage"] = taxPercentage;
                orderProduct.Rows[orderProduct.Rows.Count - 1]["Tax_Amount"] = Globals.RoundOffPrice(TypeConvert.ToDouble(orderProduct.Rows[orderProduct.Rows.Count - 1]["RE_Extended_Price"])
                    * (1 - 1 / (1 + taxPercentage / 100)), this.PrimaryDataRow["RE_LOB_Id"]);
                //DS: 12052013 - To cope with the Machine Epsilon Issue.
                orderProduct.Rows[orderProduct.Rows.Count - 1]["RE_Revenue"] = Math.Round(TypeConvert.ToDouble(orderProduct.Rows[orderProduct.Rows.Count - 1]["RE_Extended_Price"]) -
                    TypeConvert.ToDouble(orderProduct.Rows[orderProduct.Rows.Count - 1]["Tax_Amount"]), 2);
                orderProduct.Rows[orderProduct.Rows.Count - 1]["RE_Unit_Cost_Price"] = 0;
                //DS: 12052013 - To cope with the Machine Epsilon Issue.
                orderProduct.Rows[orderProduct.Rows.Count - 1]["RE_Profit"] = Math.Round(TypeConvert.ToDouble(orderProduct.Rows[orderProduct.Rows.Count - 1]["RE_Revenue"]) -
                    TypeConvert.ToDouble(orderProduct.Rows[orderProduct.Rows.Count - 1]["RE_Unit_Cost_Price"]), 2);

                //DS:06052013 - Due to the newly added order product item, totals section needs recalculation again.
                //DS: 12052013 - To cope with the Machine Epsilon Issue.
                this.PrimaryDataRow["Quote_Sub_Total"] = TypeConvert.ToDouble(this.PrimaryDataRow["Quote_Sub_Total"]) +
                    Math.Round((extraAmt - TypeConvert.ToDouble(orderProduct.Rows[orderProduct.Rows.Count - 1]["Tax_Amount"])), 2);
                this.PrimaryDataRow["Total_Taxes"] = TypeConvert.ToDouble(this.PrimaryDataRow["Total_Taxes"]) +
                    TypeConvert.ToDouble(orderProduct.Rows[orderProduct.Rows.Count - 1]["Tax_Amount"]);
                this.PrimaryDataRow["RE_Total_Price_BD"] = TypeConvert.ToDouble(this.PrimaryDataRow["RE_Total_Price_BD"]) + extraAmt;
                this.PrimaryDataRow["Quote_Total"] = TypeConvert.ToDouble(this.PrimaryDataRow["Quote_Total"]) + extraAmt;
            }
            else
                PivotalMessageBox.Show("Miscellaneous Income not defined. Please contact system Administrator", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        /// <summary>
        /// Delete the change row if there is a cash row.
        /// </summary>
        /// <param name="orderTender"></param>
        /// <param name="cashRow"></param>
        private static void DeleteChangeRow(DataTable orderTender, DataRow[] cashRow)
        {
            if (cashRow == null || cashRow.Count() == 0)
            {
                DataRow[] changeRow = orderTender.AsEnumerable().Where(a => TypeConvert.ToString(a["Tender_Type_Id__Tender_Type"]).ToUpper() == "CHANGE").ToArray();
                if (changeRow.Count() > 0)
                    orderTender.Rows.Remove(changeRow[0]);
            }
        }

        /// <summary>
        /// Calculate Change Row values.
        /// </summary>
        /// <param name="orderTender"></param>
        private void RecalculateChangeRow(DataTable orderTender)
        {
            double extraAmt = 0;
            DataRow[] changeRow = orderTender.AsEnumerable().Where(a => TypeConvert.ToString(a["Tender_Type_Id__Tender_Type"]).ToUpper() == "CHANGE").ToArray();
            DataRow[] cashRow = orderTender.AsEnumerable().Where(a => TypeConvert.ToString(a["Tender_Type_Id__Tender_Type"]).ToUpper() == "CASH").ToArray();
            if (changeRow.Count() > 0)
            {
                double sum = 0;
                sum = orderTender.AsEnumerable().Where(a => TypeConvert.ToString(a["Tender_Type_Id__Tender_Type"]).ToUpper() != "CHANGE")
                                                .Sum(a => TypeConvert.ToDouble(a["Tendered_Amount"]));

                if (sum > TypeConvert.ToDouble(this.PrimaryDataRow["Quote_Total"]))
                {
                    //DS: 12052013 - To cope with Machine Epsilon Issue.
                    extraAmt = Math.Round(TypeConvert.ToDouble(this.PrimaryDataRow["Quote_Total"]) - sum, 2);
                    double cashAmt = cashRow.Sum(a => TypeConvert.ToDouble(a["Tendered_Amount"]));

                    if (-extraAmt >= cashAmt)
                    {
                        if (changeRow.Count() > 0)
                            orderTender.Rows.Remove(changeRow[0]);

                        orderTender.Rows.Remove(cashRow[0]);
                        return;
                    }

                    //Update the change row value.
                    foreach (DataRow dr in orderTender.Rows)
                    {
                        if (TypeConvert.ToString(dr["Tender_Type_Id__Tender_Type"]).ToUpper() == "CHANGE")
                        {
                            double roundPrice = Globals.RoundOffPrice(Math.Abs(Math.Round(extraAmt, 2)), this.PrimaryDataRow["RE_LOB_Id"]);
                            if (roundPrice > 0)
                                dr["Tendered_Amount"] = -roundPrice;
                            else
                                //Delete the change row.
                                orderTender.Rows.Remove(changeRow[0]);

                            break;
                        }
                    }
                    this.PrimaryDataRow["RE_Tendered_Amount"] = sum;
                    this.PrimaryDataRow["RE_Balance_Amount"] = extraAmt < 0 ? -Globals.RoundOffPrice(Math.Abs(Math.Round(extraAmt, 2)), this.PrimaryDataRow["RE_LOB_Id"])
                        : Globals.RoundOffPrice(Math.Abs(Math.Round(extraAmt, 2)), this.PrimaryDataRow["RE_LOB_Id"]);
                    return;
                }
                else
                {
                    //Check if there is already a Change row added. If so delete that.
                    if (changeRow.Count() > 0)
                        orderTender.Rows.Remove(changeRow[0]);
                }
            }
        }

        /// <summary>
        /// Show the pop-up for the Change row.
        /// </summary>
        /// <param name="changeRow"></param>
        private void ShowChangePopup(DataRow[] changeRow)
        {
            popupChange = new Form();
            this.TableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
            this.Total = new System.Windows.Forms.Label();
            this.Label2 = new System.Windows.Forms.Label();
            this.lblTotal = new System.Windows.Forms.Label();
            this.lblChange = new System.Windows.Forms.Label();
            this.btnClose = new System.Windows.Forms.Button();
            this.TableLayoutPanel1.SuspendLayout();
            popupChange.SuspendLayout();
            // 
            // TableLayoutPanel1
            // 
            this.TableLayoutPanel1.ColumnCount = 2;
            this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 60F));
            this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 40F));
            this.TableLayoutPanel1.Controls.Add(this.Total, 0, 0);
            this.TableLayoutPanel1.Controls.Add(this.Label2, 0, 1);
            this.TableLayoutPanel1.Controls.Add(this.lblTotal, 1, 0);
            this.TableLayoutPanel1.Controls.Add(this.lblChange, 1, 1);
            this.TableLayoutPanel1.Location = new System.Drawing.Point(32, 23);
            this.TableLayoutPanel1.Name = "TableLayoutPanel1";
            this.TableLayoutPanel1.RowCount = 2;
            this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
            this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
            this.TableLayoutPanel1.Size = new System.Drawing.Size(212, 67);
            this.TableLayoutPanel1.TabIndex = 5;
            // 
            // Total
            // 
            this.Total.Anchor = System.Windows.Forms.AnchorStyles.Left;
            this.Total.AutoSize = true;
            this.Total.Font = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Total.Location = new System.Drawing.Point(3, 8);
            this.Total.Name = "Total";
            this.Total.Size = new System.Drawing.Size(45, 16);
            this.Total.TabIndex = 2;
            this.Total.Text = "Total:";
            // 
            // Label2
            // 
            this.Label2.Anchor = System.Windows.Forms.AnchorStyles.Left;
            this.Label2.AutoSize = true;
            this.Label2.Font = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Label2.Location = new System.Drawing.Point(3, 42);
            this.Label2.Name = "Label2";
            this.Label2.Size = new System.Drawing.Size(108, 16);
            this.Label2.TabIndex = 4;
            this.Label2.Text = "Change CASH:";
            // 
            // lblTotal
            // 
            this.lblTotal.Anchor = System.Windows.Forms.AnchorStyles.Right;
            this.lblTotal.AutoSize = true;
            this.lblTotal.Font = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.lblTotal.Location = new System.Drawing.Point(155, 8);
            this.lblTotal.Name = "lblTotal";
            this.lblTotal.Size = new System.Drawing.Size(54, 16);
            this.lblTotal.TabIndex = 3;
            this.lblTotal.Text = TypeConvert.ToDouble(this.PrimaryDataRow["Quote_Total"]).ToString("#0.00");
            // 
            // lblChange
            // 
            this.lblChange.Anchor = System.Windows.Forms.AnchorStyles.Right;
            this.lblChange.AutoSize = true;
            this.lblChange.Font = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.lblChange.Location = new System.Drawing.Point(155, 42);
            this.lblChange.Name = "lblChange";
            this.lblChange.Size = new System.Drawing.Size(54, 16);
            this.lblChange.TabIndex = 5;
            this.lblChange.Text = Math.Abs(TypeConvert.ToDouble(changeRow[0]["Tendered_Amount"])).ToString("#0.00");
            // 
            // btnClose
            // 
            this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.btnClose.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btnClose.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnClose.Location = new System.Drawing.Point(99, 110);
            this.btnClose.Name = "btnClose";
            this.btnClose.Size = new System.Drawing.Size(75, 34);
            this.btnClose.TabIndex = 1;
            this.btnClose.Text = "Close";
            this.btnClose.UseVisualStyleBackColor = true;
            this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
            // 
            // Tender
            // 
            popupChange.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            popupChange.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            popupChange.CancelButton = this.btnClose;
            popupChange.ClientSize = new System.Drawing.Size(274, 168);
            popupChange.ControlBox = false;
            popupChange.Controls.Add(this.TableLayoutPanel1);
            popupChange.Controls.Add(this.btnClose);
            popupChange.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            popupChange.Name = "Tender";
            popupChange.Text = "Tender";
            popupChange.TopMost = true;
            popupChange.StartPosition = FormStartPosition.CenterParent;
            TableLayoutPanel1.ResumeLayout(false);
            TableLayoutPanel1.PerformLayout();
            popupChange.ResumeLayout(false);
            popupChange.PerformLayout();
            popupChange.ShowDialog();
        }

        /// <summary>
        /// Begin teh editing of the cell.
        /// </summary>
        /// <param name="SecondarySegmentName"></param>
        /// <param name="ColumnName"></param>
        /// <param name="RowIndex"></param>
        private void BeginEditSecondaryCell(string SecondarySegmentName, string ColumnName, int RowIndex)
        {
            PivotalSecondary secOrderTenderControl = this.FormControl.GetControlByName(SecondarySegmentName) as PivotalSecondary;
            DataGridView dgOrderTenderControl = secOrderTenderControl.WindowsControl as DataGridView;
            if (!dgOrderTenderControl.IsDisposed && !dgOrderTenderControl.Disposing)
            {
                dgOrderTenderControl.CurrentCell = secOrderTenderControl.Rows[RowIndex].Cells[ColumnName];
                dgOrderTenderControl.BeginEdit(true);
            }
        }

        /// <summary>
        /// Used to set Contact information fiel required in case any Apple Care product is selcted in the 
        /// </summary>
        /// <history>
        /// #Revision   Date        Author  Description
        /// 6.0.12.0    11/06/2013  NN      Initial Version
        /// </history>
        private void SetContactRequired()
        {
            DataTable orderProduct = this.DataSet.Tables["SFA_Order__Product_SFA_Order_I"];
            DataRow[] appleCareProducts = orderProduct.AsEnumerable().Where(a => a["RE_RAE_Serial_Number"] != DBNull.Value && 
                                            TypeConvert.ToInt32(a["Quantity"]) > 0 ).ToArray();

            if (appleCareProducts != null && appleCareProducts.Length > 0)
            {
                Globals.SetFieldRequired(true, new string[] { "RE_Contact_First_Name", "RE_Contact_Last_Name", "RE_Contact_Email" });
            }
        }

        #endregion

        #region protected methods
        /// <summary>
        /// Calculate tender amount, balance amount and set it while the form loads
        /// </summary>
        protected void TotalsCalculations()
        {
            double tenderAmount = 0;
            DataTable orderTender = this.FormData.DataSet.Tables["RE_Order_Tender_Order_Id"].DefaultView.ToTable();
            tenderAmount = Math.Round(orderTender.AsEnumerable().Where(a => TypeConvert.ToString(a["Tender_Type_Id__Tender_Type"]).ToUpper() != "CHANGE")
                                                        .Sum(a => TypeConvert.ToDouble(a["Tendered_Amount"])), 2);
            this.PrimaryDataRow["RE_Tendered_Amount"] = tenderAmount;
            //DS: 12052013 - To cope with the Machine Epsilon Issue.
            this.PrimaryDataRow["RE_Balance_Amount"] = Math.Round(TypeConvert.ToDouble(this.PrimaryDataRow["Quote_Total"]) - tenderAmount, 2);
        }
        
        /// <summary>
        /// Set fields mandatory
        /// </summary>
        /// <param name="isRequired">True means mark them required else non-required.</param>
        /// <param name="secFieldsToSet">Secondary fields</param>
        protected void SetSecondaryFieldsRequired(bool isRequired, params string[] secFieldsToSet)
        {
            try
            {
                CdcSoftware.Pivotal.WindowsFormControls.TextBoxColumn columnType = null;
                PivotalSecondary tenderOrders = (PivotalSecondary)this.FormControl.GetControlByName("RE_Order_Tender_Order_Id");
                foreach (string str in secFieldsToSet)
                {
                    columnType = tenderOrders.Columns[str] as CdcSoftware.Pivotal.WindowsFormControls.TextBoxColumn;
                    columnType.Required = isRequired;
                }
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc);
            }
        }
        #endregion
    }
}
